﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VentaElectrodomesticos.Contrato;
using System.Drawing;

namespace VentaElectrodomesticos.GUI.Helpers
{
    public class TreeBuilder
    {
        private List<Categoria> categorias;
        private TreeView treeView;
        private int selectedNode;

        public TreeBuilder(List<Categoria> categorias, TreeView treeView)
        {
            this.categorias = categorias;
            this.treeView = treeView;
        }

        public void buildTree()
        {
            List<Categoria> rootsCategorias = this.categorias.Where(c => c.id_padre == 0).ToList();
            this.addNodes(rootsCategorias, treeView.Nodes);            
        }

        public void setSelectedNode(int id)
        {
            this.selectedNode = id;   
        }

        private void addNodes(List<Categoria> rootCategorias, TreeNodeCollection nodes)
        {
            foreach (Categoria categoria in rootCategorias)
            {
                TreeNode newNode = new TreeNode(categoria.Nombre);                
                newNode.Tag = categoria.Id;
                nodes.Add(newNode);
                if (this.selectedNode == categoria.Id)
                {
                    this.treeView.SelectedNode = newNode;
                    this.treeView.Select();
                }
                List<Categoria> childsCategorias = this.categorias.Where(c => c.id_padre == categoria.Id).ToList();
                if (childsCategorias.Count != 0)
                    this.addNodes(childsCategorias, newNode.Nodes);
            }
        }
    }
}
